<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖和节流</title>
</head>
<body>
  <div id="contaner">
    <input id="input" oninput="myInput()" type="text"/>
  </div>
  

  <script>
    // 防抖，在一定时间触发n秒后才执行
    let myInput = debounce()
 
    function debounce() {
      let timeLock = null
      return function() {
        clearTimeout(timeLock)
        timeLock = setTimeout(() => {
          console.log('防抖');
        }, 1000);
      }
    }
    // 节流，一定时间内只触发1次
    // 方法一：使用时间戳
    window.onresize = function() {
      myResize()
    }
    let myResize = throttle()
    function throttle() {
      var previous = 0
      return function () {
        var nowDate = Date.now()
        // 首次就能触发
        if(nowDate-previous>1000){
          console.log('节流呀');
          previous = nowDate
        }
      }
    }

    // 方法二：使用定时器
    function throttle2() {
      var timeout = null;
      return function(){
        if(!timeout){
          timeout = setTimeout(() => {
            timeout = null
            console.log('节流呀');
          }, 1000);
        }
      }   
    }
  </script>
</body>
</html>